//
//  MyViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "MyViewController.h"
#import "MyHeaderView.h"
#import "MyTableViewCell.h"
#import "MyMessViewController.h"
#import "SetViewController.h"//设置
#import "OrderViewController.h"
#import "AFNetworkHandler.h"
#import "ShopManagerVC.h"
#import "dpglViewController.h"
#import "BluetoothSetVC.h"
#import "FeWifiManHub.h"
#import "MJChiBaoZiHeader.h"
#import "OtherTypeViewController.h"
#import "CanceOrderlViewController.h"
#import "OtherController.h"
#import "ProductManagerVC.h"
#import "BusinessSchollController.h"

@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate,MytableviewDelegate,UIAlertViewDelegate> {
    NSArray *titleArr;
    NSArray *imgArr;
    NSArray *placeArr;
    NSDictionary *dataDic;
    NSString *updateURL;//版本更新地址
    FeWifiManHub *_loading;
    
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MyHeaderView *headerView;
@property (nonatomic) BOOL doHaveNotReadMess;//是否有未读信息
@property (nonatomic, strong) BaseTabBarViewController *tabBar;

@end

@implementation MyViewController

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (kNetworkNotReachability) { // 没网
        [_loading dismiss];
    }
    _doHaveNotReadMess = [AppData share].doLogin;
    if (![[ShopCommonModel share].shopname isEqualToString:@""]) {
        _headerView.userName.text = [ShopCommonModel share].shopname; // 懒猫社长三星路
        _headerView.todayOrder.text = [ShopCommonModel share].todayorderscount; // 今日订单个数
        _headerView.waitSend.text = [ShopCommonModel share].unfilledorderscount; // 代发货
        _headerView.addUserLable.text = [ShopCommonModel share].yesterdaynewuserscount; // 昨日新增用户
    }else{
        _headerView.userName.text = @""; // 懒猫社长三星路
        _headerView.todayOrder.text = @"0"; // 今日订单个数
        _headerView.waitSend.text = @"0"; // 代发货
        _headerView.addUserLable.text = @"0"; // 昨日新增用户
    }
}
#pragma mark - 头部信息
- (void)resetUserMess {
        if (![AppData share].doLogin) {
            _headerView.userName.text = @""; // 懒猫社长三星路
            _headerView.todayOrder.text = @""; // 今日订单个数
            _headerView.waitSend.text = @""; // 代发货
            _headerView.addUserLable.text = @""; // 昨日新增用户
        }else {
            _headerView.userName.text = [ShopCommonModel share].shopname; // 懒猫社长三星路
            _headerView.todayOrder.text = [ShopCommonModel share].todayorderscount; // 今日订单个数
            _headerView.waitSend.text = [ShopCommonModel share].unfilledorderscount; // 代发货
            _headerView.addUserLable.text = [ShopCommonModel share].yesterdaynewuserscount; // 昨日新增用户
        }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _headerView = [[[NSBundle mainBundle] loadNibNamed:@"MyHeaderView" owner:self options:nil] firstObject];
    _tableView.tableHeaderView = _headerView;
    _tableView.backgroundColor = BackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goLoginView) name:@"PopLoginView" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];
    
    [self loginFirst];
    [self resetUserMess];
    [self  performSelector:@selector(getVersionMessg) withObject:nil afterDelay:2];
}
#pragma mark - 收到推送通知
- (void)tongzhi:(NSNotification *)text{
//    [AppData share].baseTabVC.redLable.hidden = NO;
//    NSLog(@"%@",text.userInfo[@"textOne"]);
//    NSLog(@"%@",text.userInfo[@"textTwo"]);
//    NSLog(@"－－－－－接收到通知------");
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 144;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *Cell = @"cell";
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MyTableViewCell" owner:self options:nil] firstObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    if (indexPath.row == 0) {
        cell.imgOne.image = [UIImage imageNamed:@"dingdan_icon"];
        cell.imgTwo.image = [UIImage imageNamed:@"xiaoxi_icon"];
    }else if (indexPath.row == 1){
        cell.imgOne.image = [UIImage imageNamed:@"caiwu_icon"];
        cell.imgTwo.image = [UIImage imageNamed:@"shuju_icon"];
    }
    return cell;
}
-(void)tableViewCell:(MyTableViewCell *)cell btn:(UIButton *)btn {
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    NSInteger tag = btn.tag;
    if (indexPath.row == 0) {
        if (tag == 100) { // 订单管理
            OrderViewController *order = [[OrderViewController alloc] init];
            [self.navigationController pushViewController:order animated:YES];
        }else if (tag == 200){ // 退货管理
            OrderViewController *order = [[OrderViewController alloc]init];
            order.tuiHuoManager = YES;
            [self.navigationController pushViewController:order animated:YES];
        }
    }else if (indexPath.row == 1){
        if (tag == 100) { // 产品管理
            ProductManagerVC *product = [[ProductManagerVC alloc]init];
            [self.navigationController pushViewController:product animated:YES];
        }else if (tag == 200){ // 店铺管理
            ShopManagerVC *shop = [[ShopManagerVC alloc] init];
            [self.navigationController pushViewController:shop animated:YES];
        }
    }
}
- (void)loginFirst {//先登录
    
    [_loading removeFromSuperview];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    [self.view addSubview:_loading];
    [_loading show];
    
    NSString *name = [NSUserDefualManager getValueByKey:UserName];
    NSString *psw = [NSUserDefualManager getValueByKey:Psw];
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *cid = [userDefaul objectForKey:@"cid"];
    NSLog(@"=-----%@",cid);
    NSString *url = [NSString stringWithFormat:businessLoginUrl,name,psw,cid];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dic = result;
        NSString *r = dic[@"r"];
        if ([r isEqualToString:@"T"]) {
            NSDictionary *userMess = dic[@"shopinfo"];
            NSDictionary *userMess111 = dic[@"scoreinfo"];
            /***********懒猫掌柜****************/
            [AppData share].doLogin = YES;
            [AppData share].mobile = userMess[@"mobile"];
            [AppData share].username = userMess[@"username"];
            [AppData share].shoplogo = userMess[@"shoplogo"];
            [AppData share].shopname = userMess[@"shopname"];
            [AppData share].contacter = userMess[@"contacter"];
            [AppData share].shortintroduce = userMess[@"shortintroduce"];
            [AppData share].shopnote = userMess[@"shopnote"];
            [AppData share].openingend = userMess[@"openingend"];
            [AppData share].openingstart = userMess[@"openingstart"];
            [AppData share].serveramount = userMess[@"serveramount"];
            [AppData share].minSentamount = userMess[@"minSentamount"];
            [AppData share].privatekey = userMess[@"privatekey"];
            [AppData share].totalincome = userMess111[@"totalincome"];
            [AppData share].cashbalance = userMess111[@"cashbalance"];
            [NSUserDefualManager storageValue:@"1" forKey:@"doLogin"];
            [[AppData share].baseTabVC theShoppingCartCount:userMess[@"shopcart"]];
        }else {
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:^{
            }];
        }
        [self getData];
    }];
}
-(void)getData {
    if (kNetworkNotReachability) { // 没网
        return;
    }
    if (![AppData share].doLogin) {
        [self loginFirst];
    }
    NSString *url = [NSString stringWithFormat:indexUrl,[AppData share].username,[AppData share].username];
    dataDic = [NSDictionary dictionary];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        dataDic = result;
        if ([dataDic[@"r"] isEqualToString:@"T"]) {
            /**
             "username": "lanmao0823",
             "shopname": "懒猫社长-国际华城体验店",
             "shoplogo": "http://admintest.ivpin.com/uploads/MallShop/ec561f66-f5dd-45dd-8a84-45f917989ae3.jpg",
             "cashbalance": "6125.42",   //账户余额
             "totalincome": "0.00",      //累计收入
             "todayorderscount": "0",    //今天订单总数
             "unfilledorderscount": "0",  //待发货订单数
             "yesterdaynewuserscount": "0",//昨天新增用户总数
             "noreadnoticecount": "0"   //未读消息总数
             
             **/
            [ShopCommonModel share].username = dataDic[@"username"];
            [ShopCommonModel share].shopname = dataDic[@"shopname"];
            [ShopCommonModel share].shoplogo = dataDic[@"shoplogo"];
            [ShopCommonModel share].cashbalance = dataDic[@"cashbalance"];
            [ShopCommonModel share].totalincome = dataDic[@"totalincome"];
            [ShopCommonModel share].todayorderscount = dataDic[@"todayorderscount"];
            [ShopCommonModel share].unfilledorderscount = dataDic[@"unfilledorderscount"];
            [ShopCommonModel share].yesterdaynewuserscount = dataDic[@"yesterdaynewuserscount"];
            [ShopCommonModel share].noreadnoticecount = dataDic[@"noreadnoticecount"];
            if ([dataDic[@"noreadnoticecount"] floatValue] > 0) { // 是否有未读消息
                [AppData share].baseTabVC.redLable.hidden = NO;
            }else{
                [AppData share].baseTabVC.redLable.hidden = YES;
            }
            [self resetUserMess]; // 头部信息显示
        }else{
            
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
    }];
}
#pragma mark - 版本升级
- (void)getVersionMessg {
    NSString *banbenID = @"1"; // 版本号
    NSString *url = @"";
    if ([banbenID isEqualToString:@"1.0.1"]) { // APPStore版本升级
        url = [NSString stringWithFormat:Updatestore,[Utils md5SignStr],@"1.0.2"];
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"IOSstore"];
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    return ;
                }
                if ([need isEqualToString:@"false"]) {//不强制
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
//===========================================================
    }else{ // 企业版本号
        url = [NSString stringWithFormat:UpdateVersion,[Utils md5SignStr],@"1.0.4"]; // 1.0.4
        [NTNetUtil sendRequestWithUrl:url requestName:UpdateVersion method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *suc = dic[@"r"];
            if ([suc isEqualToString:@"T"]) {
                NSDictionary *ios = dic[@"iOS"];
                NSString *need = [ios[@"need"] safeString];
                NSString *note = [ios[@"note"] safeString];
                NSString *title = [ios[@"title"] safeString];
                NSString *isnew = [ios[@"isnew"] safeString];
                if ([isnew isEqualToString:@"false"]) {
                    return ;
                }
                if ([need isEqualToString:@"false"]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
                    alert.tag = 100;
                    [alert show];
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:note delegate:self cancelButtonTitle:@"更新" otherButtonTitles:nil, nil];
                    alert.tag = 101;
                    [alert show];
                }
                updateURL = [ios[@"url"] safeString];
            }
        }];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100) {
        if (buttonIndex == 1) { // 更新
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",updateURL]]];
        }
    }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",updateURL]]];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
